package com.andy.nature.view

import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.Window
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsAnimationCompat
import androidx.core.view.WindowInsetsCompat

class KeyBoardLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : LinearLayoutCompat(context, attrs, defStyle) {

    init {
        setWindowInsetsAnimation((context as? Activity)?.window)
    }

    private fun setWindowInsetsAnimation(window: Window?) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            window?.setDecorFitsSystemWindows(false)
        }
        ViewCompat.setWindowInsetsAnimationCallback(this, object : WindowInsetsAnimationCompat.Callback(DISPATCH_MODE_CONTINUE_ON_SUBTREE) {
            override fun onProgress(insets: WindowInsetsCompat, runningAnimations: MutableList<WindowInsetsAnimationCompat>): WindowInsetsCompat {
                val softInputHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
                val navigationBarsHeight = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom
                imeStateListener?.onImeBottomChanged(softInputHeight - navigationBarsHeight)
                val inputHeight = if (softInputHeight > navigationBarsHeight) softInputHeight - navigationBarsHeight else softInputHeight
                imeStateListener?.onImeFixNavigationBarBottomChanged(inputHeight)
                return insets
            }

            override fun onEnd(animation: WindowInsetsAnimationCompat) {
                super.onEnd(animation)
                if (!isImeShow()) {
                    imeStateListener?.onImeClose()
                }
            }

        })
    }

    /**
     * 键盘是否显示
     */
    fun isImeShow(): Boolean {
        val decorView = (context as? Activity)?.window?.decorView ?: return false
        return ViewCompat.getRootWindowInsets(decorView)?.isVisible(WindowInsetsCompat.Type.ime()) ?: false
    }

    fun setImeListener(imeStateListener: ImeStateListener) {
        this.imeStateListener = imeStateListener
    }

    var imeStateListener: ImeStateListener? = null

    interface ImeStateListener {
        fun onImeBottomChanged(height: Int)
        fun onImeFixNavigationBarBottomChanged(height: Int)
        fun onImeClose()
    }
}